const KEY_ACCESS_TOKEN = "access_token"
const KEY_REFRESH_TOKEN = "refresh_token"
const KEY_ACCOUNT = "account"
const KEY_ROLES = "roles"
const KEY_USER_INFO = "userInfo"
const PUB_KEY = "-----BEGIN PUBLIC KEY-----MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgGLHLSBdS0waflUq6ot6lSOIk8ky3pIMI8ZUrpAFqncw083lPImWOpZ7LHOoqW2eHgRICu58K69kFSY1RJt5ko9CmO0MG4E6erUV7ODB0+k+IXVjcV4LBQuSw5dJCDz9RF8UplYmOxFaTMaeddJsV40QDJTHa5IhKg4LAuCTIJ0PAgMBAAE=-----END PUBLIC KEY-----";

define([
  'CacheUtil', 'md5', 'jsencrypt'
], function (cacheUtil, md5, JSEncrypt) {

  function _getKey(key) {
    if (IS_DEBUG) {
      return key;
    } else {
      return md5(key);
    }
  };

  function rsaEncode(data) {
    var encryptor = new JSEncrypt();
    encryptor.setPublicKey(PUB_KEY) //设置公钥
    var rsaData = encryptor.encrypt(data); // 对内容进行加密
    return rsaData;
  };

  function getRefreshToken() {
    return cacheUtil.get(_getKey(KEY_REFRESH_TOKEN));
  };

  function getAccessToken() {
    return cacheUtil.get(_getKey(KEY_ACCESS_TOKEN));
  };

  function isLogin() {
    return getRefreshToken() != null;
  };
  /**
   * 缓存信息
   * @param {*} oauth 授权信息
   * @param {*} user  用户信息
   */
  function saveOauth(oauth) {
    if (!oauth) return
    cacheUtil.set(_getKey(KEY_ACCESS_TOKEN), oauth.accessToken, oauth.expiresIn - 300)
    cacheUtil.set(_getKey(KEY_REFRESH_TOKEN), oauth.refreshToken, 7 * 24 * 60 * 60)
  };

  function saveUser(user) {
    if (!user) return
    cacheUtil.set(_getKey(KEY_ACCOUNT), user.account, -1)
    cacheUtil.set(_getKey(KEY_ROLES), JSON.stringify(user.roles), -1)
    cacheUtil.set(_getKey(KEY_USER_INFO), JSON.stringify(user), -1)
  }

  function getAccount() {
    return cacheUtil.get(_getKey(KEY_ACCOUNT));
  }

  function getUserInfo() {
    let json = cacheUtil.get(_getKey(KEY_USER_INFO))
    return JSON.parse(json)
  }

  function getRoles() {
    var jsonStr = cacheUtil.get(_getKey(KEY_ROLES));
    if (jsonStr == null) return [];
    return JSON.parse(jsonStr);
  }

  function getMainRole() {
    var roles = getRoles();
    return roles[0].roleCode;
  }

  function clearCache() {
    cacheUtil.clear();
  }

  return {
    isLogin: isLogin,
    saveOauth: saveOauth,
    saveUser: saveUser,
    getAccessToken: getAccessToken,
    getRefreshToken: getRefreshToken,
    getAccount: getAccount,
    getMainRole: getMainRole,
    getRoles: getRoles,
    rsaEncode: rsaEncode,
    getUserInfo: getUserInfo,
    clearCache: clearCache
  }

});